<?php

/**
 * Author：晴天 QQ：1186258278
 * Creation：2020/3/23 20:21
 * Filename：UserConf.php
 * 用户配置载入
 */

namespace extend;

use config;
use login_data;
use Medoo\DB\SQL;
use price;

class UserConf
{
    public static function judge($dome = null)
    {
        global $conf;
        if (isset($_COOKIE['league']) && $conf['userdomaintype'] == 2) {
            $domain = xiaochu_de($_COOKIE['league']);
        } else $domain = href();
        if ($dome <> null) $domain = $dome;
        $DB = SQL::DB();
        $UserData = $DB->get('user', '*', [
            'domain' => $domain,
            'state' => 1,
            'grade[>=]' => $conf['userleaguegrade'],
        ]);
        if (!$UserData) return false;
        return $UserData;
    }

    /**
     * @param int $gid
     * @return int
     * 计算当前加盟站点对此商品的提价比例！
     */
    public static function GoodsPrice($gid = -1, $User = false)
    {
        global $conf, $accredit;
        if (empty($_SESSION['UserGoods'])) return 0;
        $UserGoods = json_decode(xiaochu_de($_SESSION['UserGoods'], $accredit['token']), TRUE);
        if (empty($UserGoods['uid']) || empty($UserGoods['grade'])) return 0;
        if (count($UserGoods['GoodsRis']) == 0) return 0;

        if ($UserGoods['grade'] < $conf['usergradeprofit']) return 0;
        if (!empty($_COOKIE['THEKEY'])) {
            /**
             * 验证1、自己站点！
             * 验证2、等级>=当前站点站长！
             */
            if ($User == false || $User == -1) $User = login_data::user_data();
            if ($User != false && $User['id'] == $UserGoods['uid']) return 0; //是站长
            if ($User['grade'] >= $UserGoods['grade']) return 0; //同等级
        }

        if (array_key_exists($gid, $UserGoods['GoodsRis'])) {
            if (empty($UserGoods['GoodsRis'][$gid]['rise']) || $UserGoods['GoodsRis'][$gid]['rise'] <= 0) return 0;
            return $UserGoods['GoodsRis'][$gid]['rise'];
        } else return 0;
    }

    /**
     * @return array
     * 取出当前加盟店内下架的商品ID
     */
    public static function GoodsHide()
    {
        global $conf, $accredit;
        if (empty($_SESSION['UserGoods'])) return [];
        $UserGoods = json_decode(xiaochu_de($_SESSION['UserGoods'], $accredit['token']), TRUE);
        if (empty($UserGoods['uid']) || empty($UserGoods['grade'])) return [];
        if (count($UserGoods['GoodsRis']) == 0) return [];
        if ($UserGoods['grade'] < $conf['usergradegoodsstate']) return [];
        $Deploy = $UserGoods['GoodsRis']; //商品配置
        $Data = [];
        foreach ($Deploy as $key => $value) {
            if ($value['state'] == -1) {
                $Data[] = $key;
            } else continue;
        }
        return $Data;
    }

    public static function Conf($data)
    {
        global $accredit, $_QET;
        $_SESSION['UserGoods'] = null;
        if (md5_file(SYSTEM_ROOT . xiaochu_de('Z1nVuLmFkbWluLnBocAO0O0OO0O0O', '1')) <> 'dc37b93ee6de7c0846f03f7d33677ab1') die();
        if ($data['userleague'] <> 1 || !empty($_COOKIE['ADMIN_TOKEN'])) return $data;
        if (!empty($_COOKIE['league']) && $data['userdomaintype'] == 2) {
            $domain = xiaochu_de($_COOKIE['league']);
            if ($domain == '') setcookie("league", null, time() - 3600 * 12 * 30, '/');
        } else $domain = ($data['userdomaintype'] == 1 ? href() : $_QET['t']);
        if ($data['userdomaintype'] == 2 && !empty($_QET['t'])) {
            setcookie("league", xiaochu_en($domain), time() + 3600 * 12 * 30, '/');
        } else if ($data['userdomaintype'] == 1 && !empty($_COOKIE['league'])) {
            setcookie("league", null, time() - 3600 * 12 * 30, '/');
            $domain = href();
        }
        if (!$domain) return $data;
        $DB = SQL::DB();
        $UserData = $DB->get('user', ['id', 'configuration', 'grade', 'pricehike'], [
            'domain' => $domain,
            'state' => 1,
            'grade[>=]' => $data['userleaguegrade']
        ]);
        if (!$UserData) return $data;
        $_SESSION['UserGoods'] = xiaochu_en(json_encode(['uid' => $UserData['id'], 'grade' => $UserData['grade'], 'GoodsRis' => ($UserData['pricehike'] == '' ? [] : json_decode($UserData['pricehike'], TRUE))], JSON_UNESCAPED_UNICODE), $accredit['token']);
        if ($UserData['configuration'] == '') return $data;
        $UserC = config::common_unserialize($UserData['configuration']);
        $data = array_merge($data, $UserC);
        $data['notice_top'] = htmlspecialchars_decode(base64_decode($UserC['notice_top'], TRUE));
        $data['notice_check'] = htmlspecialchars_decode(base64_decode($UserC['notice_check'], TRUE));
        $data['notice_bottom'] = htmlspecialchars_decode(base64_decode($UserC['notice_bottom'], TRUE));
        $data['PopupNotice'] = htmlspecialchars_decode(base64_decode($UserC['PopupNotice'], TRUE));
        return $data;
    }

    /**
     * @param $order
     * @param $gid
     * @param $price
     * @param $type
     * @param $num
     * @param $input
     * @return bool
     * 提成分配
     */
    public static function PushMoney($Uid, $order, $gid, $price, $type, $num, $input)
    {
        global $conf;
        $DB = SQL::DB();
        $domain_user = self::judge();
        if ($domain_user == false && $conf['userdomaintype'] == 2 && file_exists(ROOT . 'includes/extend/log/Order/' . $order . '.log')) {
            $domain_user = self::judge(file_get_contents(ROOT . 'includes/extend/log/Order/' . $order . '.log'));
        }

        if ($domain_user <> false) {
            $gid_data = $DB->get('goods', '*', [
                'gid' => $gid
            ]);
            if (!$gid_data) return false;

            $Goods = $gid_data;

            $Sku = $input;

            if ($Goods['specification'] == 2) {
                $SpRule = RlueAnalysis($Goods['specification_set'], $Goods, 1, false, $domain_user);
                if ($SpRule == -1) return false;
                $SkuData = [
                    'data' => $SpRule,
                    'SKU' => json_decode($Goods['specification_sku'], TRUE),
                ];
                $Index = -1;
                foreach ($SkuData['SKU'] as $Key => $value) {
                    if (is_array($value)) {
                        if ($value[0] == $Sku[0] && $value[1] == $Sku[1]) $Index = $Key;
                    } else {
                        if ($value == $Sku[0]) $Index = $Key;
                    }
                }
                if ($Index == -1) return false;
                $DataRule = $SkuData['data']['Parameter'][$Index];
                $gid_data['price'] = $DataRule['price'];
                $gid_data['points'] = $DataRule['points'];
                $pricer['level'] = $SkuData['data']['level'];
            } else {
                $pricer = price::price_uid(login_data::user_grade($domain_user['id']), $gid_data['profits'], $gid_data['money'], $gid_data['custom']);
                $gid_data['price'] = $pricer['price'];
                $gid_data['points'] = $pricer['points'];
            }

            $points_domain = $gid_data['points'] * $num;
            if ($type == 1) {
                if ($gid_data['freight'] <> -1) {
                    $freight = $DB->get('freight', '*', [
                        'id' => $gid_data['freight']
                    ]);
                    if ($freight) {
                        $price_domain = price::freight($freight, $input, $gid_data['price'], $num);
                    } else $price_domain = $gid_data['price'] * $num;
                } else $price_domain = $gid_data['price'] * $num;

                $Money = $price - $price_domain;
                if ($price <= $price_domain) $Money = 0;
                self::PaidCommission($domain_user, $Money, 1, '余额提成', '用户[' . ($Uid == -1 ? '游客' : $Uid) . ']在您的站点购买了商品' . str_replace("！", "", $gid_data['name']) . '，根据Ta购买的价格和您(' . str_replace("！", "", $pricer['level']) . ')的购买价来计算,特奖励您[Money]元提成,继续加油哦！' . ('(' . $order . ',[Money],余额提成)'), $order);
            } else {
                $Money = $price - $points_domain;
                if ($price <= $points_domain) $Money = 0;
                self::PaidCommission($domain_user, $Money, 2, '货币提成', '用户[' . ($Uid == -1 ? '游客' : $Uid) . ']在您的站点购买了商品' . str_replace("！", "", $gid_data['name']) . '，根据Ta兑换商品的' . $conf['currency'] . '数和您(' . str_replace("！", "", $pricer['level']) . ')的兑换价来计算，特奖励您[Money]' . $conf['currency'] . ',继续加油哦！' . ('(' . $order . ',[Money],货币提成)'), $order);
            }
        } else return false;
    }

    /**
     * @param $Order 退款订单号
     * @param $Type 方式，货币提成/余额提成
     */
    public static function DeductCommission($Order, $Type)
    {
        $DB = SQL::DB();
        $Res = $DB->select('journal', ['content', 'uid', 'id'], [
            'content[~]' => $Order,
            'name' => $Type
        ]);

        if (!$Res) return false;
        if (count($Res) == 0) return false;
        $I = 0;
        foreach ($Res as $Log) {
            $OrderLog = explode(',', getSubstr($Log['content'], '！(', ')'));
            if (empty($OrderLog[0]) || empty($OrderLog[1]) || empty($OrderLog[2])) return false;

            if ($Type == '货币提成') {
                $Res = $DB->update('user', [
                    'currency[-]' => $OrderLog[1]
                ], [
                    'id' => $Log['uid'],
                ]);
            } else {
                $Res = $DB->update('user', [
                    'money[-]' => $OrderLog[1]
                ], [
                    'id' => $Log['uid'],
                ]);
            }

            if ($Res) {
                @$DB->update('journal', [
                    'name' => $Type . '(无效)',
                    'count' => 0
                ], [
                    'id' => $Log['id']
                ]);
                ++$I;
            }
        }

        if ($I == count($Res)) return true;
        return false;
    }

    /**
     * @param $Uid  收到奖励的用户ID
     * @param $Price 收到奖励的金额
     * @param $type 收到奖励的方式
     * @param $name 商品名称
     * @param $msg 奖励的内容
     * @param $Money 原始金额
     * 奖励发发
     */
    public static function PaidCommission($User, $Price, $type, $name, $msg, $order, $Money = -1)
    {
        global $conf;
        $DB = SQL::DB();
        $Price = (float)$Price;
        if ($Money == -1) $Money = $Price;
        if ($User['superior'] >= 1) {
            $Mid = RatingParameters($User);
            if ($Mid == -1) return false;
            $ActualProfit = ($Mid['ActualProfit'] - 0);
            $ProfitThreshold = ($Mid['ProfitThreshold'] - 0);
            $PriceS = ($Price / 100) * $ActualProfit;
            $PriseT = $Price - $PriceS;
            $Threshold = ($Money / 100) * $ProfitThreshold;
            if ($PriceS >= $Price) $PriceS = $Price;
            $PrType = true;
            if ($PriceS <= $Threshold) $PrType = false;
            if ($PrType == true) {
                $UserTs = $DB->get('user', '*', ['id' => $User['superior']]);
                if (!$UserTs || $UserTs['state'] != 1 || $UserTs['grade'] <= $User['grade']) $PrType = false;
            }
            if ($PrType == true) $Price = $PriceS;
        } else $PrType = false;

        $msg = str_replace('[Money]', $Price, $msg);

        userlog($name, $msg, $User['id'], $Price);

        $field = ($type == 1 ? 'money' : 'currency');
        $Res = $DB->update('user', [
            $field . '[+]' => $Price,
        ], [
            'id' => $User['id']
        ]);

        if (!$Res) {
            userlog('奖励失败', '提成奖励失败,无法写入奖励！' . $DB->error() . ',奖励' . ($type == 1 ? '金额' : '积分') . $Price . '应得用户ID:' . $User['id'], $User['id']);
        } else {
            if ($PrType == true) {
                $msg = '您的分销下级[' . $User['id'] . ']为您提供了[Money]' . ($type == 1 ? '元' : $conf['currency']) . '提成奖励，再接再厉哦！' . ('(' . $order . ',[Money],' . ($type == 1 ? '余额' : '货币') . '提成)');
                self::PaidCommission($UserTs, $PriseT, $type, $name, $msg, $order, $Money);
            }
            return true;
        }
    }

    /**
     * @param $dowid
     * @param $money
     * @param int $uid
     * @param $grade
     * @return bool
     * 升级提成发放
     */
    public static function Commission($dowid, $money, $uid = 0, $grade)
    {
        global $conf;
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $domain_user = self::judge();
        $money = (float)$money * ($conf['userupgradeprofit'] / 100);
        if ($money <= 0) $money = 0;
        if (($uid == 0 and $domain_user == false) || $conf['usergradecost'] == -1 || $dowid == $domain_user['id']) return false;

        if ($domain_user <> $uid && $domain_user <> false && $uid <> 0) {
            $User1 = $DB->get_row("SELECT id,configuration,grade FROM `sky_user` WHERE `id` = '$uid' AND `state` = 1 AND `grade` >= '{$conf['userleaguegrade']}' LIMIT 1");
            if ($User1) {
                $money = $money / 2;
                if ($User1['grade'] >= $grade) {
                    userlog('升级提成', '您的下级[' . $dowid . ']将用户等级提升到了' . $grade . '级,特奖励您' . $money . '元下级升级奖励！', $uid, $money);
                    @$DB->query("UPDATE `sky_user` SET `money`= money + $money WHERE (`id`='$uid')");
                }
                if ($domain_user['grade'] >= $grade) {
                    userlog('升级提成', '用户[' . $dowid . ']在您的站点将等级提升到了' . $grade . '级,特奖励您' . $money . '元下级升级奖励！', $domain_user['id'], $money);
                    @$DB->query("UPDATE `sky_user` SET `money`= money + $money WHERE (`id`='{$domain_user['id']}')");
                }
            } else {
                if ($User1['grade'] >= $grade) {
                    userlog('升级提成', '您的下级[' . $dowid . ']将用户等级提升到了' . $grade . '级,特奖励您' . $money . '元下级升级奖励！', $uid, $money);
                    @$DB->query("UPDATE `sky_user` SET `money`= money + $money WHERE (`id`='$uid')");
                }
            }
        } else {
            if ($domain_user <> false) {
                if ($domain_user['grade'] >= $grade) {
                    userlog('升级提成', '您的下级[' . $dowid . ']将用户等级提升到了' . $grade . '级,特奖励您' . $money . '元下级升级奖励！', $domain_user['id'], $money);
                    @$DB->query("UPDATE `sky_user` SET `money`= money + $money WHERE (`id`= '{$domain_user['id']}' )");
                }
            } else {
                $User1 = $DB->get_row("SELECT id,configuration,grade FROM `sky_user` WHERE `id` = '$uid' AND `state` = 1 AND `grade` >= '{$conf['userleaguegrade']}' LIMIT 1");
                if (!$User1) return false;
                if ($User1['grade'] >= $grade) {
                    userlog('升级提成', '您的下级[' . $dowid . ']将用户等级提升到了' . $grade . '级,特奖励您' . $money . '元下级升级奖励！', $uid, $money);
                    @$DB->query("UPDATE `sky_user` SET `money`= money + $money WHERE (`id`='$uid')");
                }
            }
        }
    }
}
